//    Travel US - For users of travel.usairways.com
//    intended for US Airways employees and their dependents
//    This app will help you track your flights and display
//    Availability, flight status and other non-rev info
//    Copyright (C) 2014  Renats Stozkovs
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.bc004346.travelus;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bc004346.travelus.DataAccess.AsyncTasks.LoginTaskFragment;
import com.bc004346.travelus.Model.Interface.ILoginCallback;
import com.bc004346.travelus.Model.TravelUsException;
import com.bc004346.travelus.Utility.Utility;

import static com.bc004346.travelus.Utility.Utility.LOGIN_TASK_TAG;
import static com.bc004346.travelus.Utility.Utility.onActivityStart;
import static com.bc004346.travelus.Utility.Utility.onActivityStop;

/**
 * Activity which displays a action_item_menu screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity implements ILoginCallback {

    //<editor-fold desc="Private Members">

    private TextView mTextViewStatus;
    private Button mButtonSave;
    private TextView mTextViewUsername;
    private TextView mTextViewPassword;
    private ProgressBar mProgressBar;
    private FragmentManager mFragmentManager;

    //</editor-fold>

    //<editor-fold desc="Properties">

    String getUsername() {
        return mTextViewUsername.getText() == null ? "" : mTextViewUsername.getText().toString().trim();
    }

    String getPassword() {
        return mTextViewPassword.getText() == null ? "" : mTextViewPassword.getText().toString().trim();
    }

    //</editor-fold>

    //<editor-fold desc="Overrides">

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_login);
        SetupUiEvents();
    }

    @Override
    protected void onStart() {
        super.onStart();
        onActivityStart(this);
    }

    @Override
    protected void onStop() {
        try {
            super.onStop();
            Utility.onStop(this);
            onActivityStop(this);
        } catch (Exception e) {
            Utility.log(e, this);
        }
    }

    @Override
    public void onLoginPostExecute(Boolean success, Exception e) {

        try {
            mButtonSave.setEnabled(true);
            mProgressBar.setVisibility(View.INVISIBLE);

            if (success) {
                Utility.username = getUsername();
                Utility.password = getPassword();
                Intent resultIntent = new Intent();
                setResult(RESULT_OK, resultIntent);
                finish();
            } else {
                mButtonSave.setText(getString(R.string.activity_login_button_login));
                mButtonSave.setEnabled(true);
                if (e != null && e.getClass() == TravelUsException.class)
                    mTextViewStatus.setText(e.getMessage());
                else if (e != null && e.getClass() != TravelUsException.class) {
                    mTextViewStatus.setText(String.format(getString(R.string.common_login_has_failed), e.getMessage()));
                    Utility.log(e, this);
                } else {
                    //SpannableString s = new SpannableString(getString(R.string.activity_login_textView_message_error));
                    //s.setSpan(new UnderlineSpan(), 90, 117, 0);
                    mTextViewStatus.setText(getString(R.string.activity_login_textView_message_error));
                    Linkify.addLinks(mTextViewStatus, Linkify.WEB_URLS);
                    mTextViewStatus.setLinkTextColor(Color.parseColor("#ffffff"));
                }

                LoginTaskFragment mLoginTaskFragment =
                        (LoginTaskFragment) mFragmentManager.findFragmentByTag(LOGIN_TASK_TAG);
                if (mLoginTaskFragment != null)
                    mFragmentManager.beginTransaction().remove(mLoginTaskFragment).commitAllowingStateLoss();
            }
        } catch (Exception e1) {
            Utility.log(e1, this);
        }
    }

    //</editor-fold>

    //<editor-fold desc="Private Methods">

    private void SetupUiEvents() {
        try {
            Utility.onStart(this);
            mButtonSave = (Button) findViewById(R.id.activity_login_button_login);
            mTextViewStatus = (TextView) findViewById(R.id.activity_login_textView_message);
            mTextViewUsername = (TextView) findViewById(R.id.activity_login_textView_login);
            mTextViewPassword = (TextView) findViewById(R.id.activity_login_textView_password);
            mButtonSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    HandleLoginClick();
                }
            });
            mProgressBar = (ProgressBar) findViewById(R.id.activity_login_progressBar);

            mFragmentManager = getFragmentManager();
            LoginTaskFragment mLoginTaskFragment =
                    (LoginTaskFragment) mFragmentManager.findFragmentByTag(LOGIN_TASK_TAG);

            // If the Fragment is non-null, then it is currently being
            // retained across a configuration change.
            if (mLoginTaskFragment == null) {
                mTextViewUsername.setText(Utility.username);
                mTextViewPassword.setText(Utility.password);
            } else mButtonSave.setEnabled(false);
        } catch (Exception e) {
            Utility.log(e, this);
        }
    }

    private void HandleLoginClick() {
        try {
            mProgressBar.setVisibility(View.VISIBLE);
            mButtonSave.setEnabled(false);
            mButtonSave.setText(getString(R.string.common_logging_in));
            LoginTaskFragment mLoginTaskFragment =
                    (LoginTaskFragment) mFragmentManager.findFragmentByTag(LOGIN_TASK_TAG);

            // If the Fragment is non-null, then it is currently being
            // retained across a configuration change.
            if (mLoginTaskFragment == null) {
                mLoginTaskFragment =
                        LoginTaskFragment.newInstance(
                                getUsername(),
                                getPassword());
                mFragmentManager.beginTransaction().add(mLoginTaskFragment, LOGIN_TASK_TAG).commit();
            }
        } catch (Exception e) {
            Utility.log(e, this);
        }
    }

    //</editor-fold>
}
